//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/9/26.
//  Copyright (c) 2015年 xuzenghui. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager

- (void)requestWithType:(RequestType)type urlString:(NSString*)urlString parDic:(NSDictionary*)parDic finish:(RequestFinish)finish error:(RequestError)error
{
     //  拿到参数之后 进行请求
    NSURL *url = [NSURL URLWithString:urlString];
     //  创建可变的URLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    if (type == POST) {
        //  设置请求方式
        [request setHTTPMethod:@"POST"];
        //  设置请求参数的Body体
        if (parDic.count > 0){
            NSData *data = [self parDicToDataWithDic:parDic];
            [request setHTTPBody:data];
        }
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            finish(data);
        }
        else
        {
            error(connectionError);
        }
    }];
}

+ (void)requestWithType:(RequestType)type urlString:(NSString*)urlString parDic:(NSDictionary*)parDic finish:(RequestFinish)finish error:(RequestError)error;
{
     [[[PKRequestManager alloc]init] requestWithType:type urlString:urlString parDic:parDic finish:finish error:error];
}

//  把字典转为post请求所需要的参数
- (NSData*)parDicToDataWithDic:(NSDictionary*)dic
{
    NSMutableArray *arr = [NSMutableArray array];
    //  遍历字典得到每一个建，得到所有的Key ＝ Value的字符串
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [arr addObject:str];
    }
    //  数组里所有的Key ＝ Value的字符串通过&符号连接
    NSString *parString = [arr componentsJoinedByString:@"&"];
    return  [parString dataUsingEncoding:NSUTF8StringEncoding];
}
@end
